package com.gopay.webtest.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.http.HttpStatus;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by Johnson on 2017/1/4.
 */
public class UploadFileUtil {
    public static String uploadFile(Map<String,Object> params,String baseUrl) {
        if (!params.containsKey("file")) {
            throw new IllegalArgumentException("请上传图片");
        }
        File file = (File) params.get("file");
        if (!file.exists()) {
            throw new IllegalArgumentException("上传图片不存在,或图片格式不正确");
        }
        if(file.length() > 2*1024*1024) {
            throw new IllegalArgumentException("上传图片太大，请上传2M以下的图片");
        }
        if (baseUrl == null || baseUrl.trim().length() == 0) {
            throw new IllegalArgumentException("invalid url : " + baseUrl);
        }
        String queryString = mapToQueryString(params, "utf-8");
        int index = baseUrl.indexOf("?");
        if (index > 0) {
            baseUrl += "&" + queryString;
        } else {
            baseUrl += "?" + queryString;
        }
        PostMethod postMethod = new PostMethod(baseUrl);
        try {
            FilePart fp = new FilePart("file", file);
            Part[] parts = { fp };
            MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
            postMethod.setRequestEntity(mre);
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);//设置连接时间
            int status = client.executeMethod(postMethod);
            if (status == HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            } else {
                throw new RuntimeException("上传请求异常");
            }
        } catch (Exception e) {
            throw new RuntimeException("上传请求异常");
        } finally {
            // 释放连接
            postMethod.releaseConnection();
        }
    }

    public static String mapToQueryString(Map<String, Object> parameters, String charSet)
    {
        String queryString = "";
        if (parameters != null && !parameters.isEmpty()) {
            for (String key : parameters.keySet()) {
                try {
                    Object value = parameters.get(key);
                    if (value instanceof String) {
                        queryString += key + "=" +
                                URLEncoder.encode(value == null ? "" : value.toString(), charSet) + "&";
                    }
                } catch (UnsupportedEncodingException e) {
                    throw new IllegalArgumentException("invalid charset : " + charSet);
                }
            }
            if (queryString.length() > 0) {
                queryString = queryString.substring(0, queryString.length() - 1);
            }
        }
        return queryString;
    }

}
